import * as vscode from 'vscode';
import { IDocData, fetchApiDoc } from '../api/doc';


export default function docHover(context: vscode.ExtensionContext) {
  vscode.languages.registerHoverProvider(
    '*',
    new class implements vscode.HoverProvider {
      async provideHover(
        _document: vscode.TextDocument,
        _position: vscode.Position,
        _token: vscode.CancellationToken
      ): Promise<vscode.Hover | null> {
        const editor = vscode.window.activeTextEditor;
        const text = editor?.document.getText(editor.selection);

        if (text) {
          let res:IDocData[]|null = null;

          try {
            res = await fetchApiDoc<IDocData[]>(text) as IDocData[];
          } catch (err) {
            console.log(err);
          }

          if (!res) return Promise.resolve(null);

          const contentList:string[][] = res.map((item:any) => {
            return [
              `[${item.link}](${item.router})`,
              `${item.name}`,
              `${item.desc}`,
              `更新时间：${item.updatedAt}`,
              `-----`,
            ];
          });
          let contents:string[] = [];

          for (let content of contentList) {
            contents = contents.concat(content);
          }
          return new vscode.Hover(contents);
        }
        return null;
      }
    }()
  );
}
